// -------------------------源码------------------------
/**
 * 实现原理：
 * 1.获取新的值
 * 2.赋值
 * 3.重新渲染视图
 */

const MyReact = (() => {
  //定义单个state数据时的源码实现
  // let state;

  // function useState(initialState) {
  //   //初始值
  //   _state = _state === undefined ? initialState : _state;

  //   //参数可以是原始值,也可以是函数
  //   const _setState = (newState) => {
  //     if (typeof newState === 'function') {
  //       //函数时
  //       _state = newState(_state);
  //     } else {
  //       //原始值时 将新的newState值赋值给_state
  //       _state = newState;
  //     }

  //     //赋值完毕时重新渲染更新视图
  //     render();
  //   };

  //   return [_state, _setState];
  // }

  //定义多个state数据时的源码实现
  const states = [],
    stateSetters = [];

  let stateIndex = 0;

  //对应stateIndex来创建state
  function createState(initialState, stateIndex) {
    // states[stateIndex]有值时
    return states[stateIndex] !== undefined ? states[stateIndex] : initialState;
  }

  //对应stateIndex来创建stateSetter
  function createStateSetter(stateIndex) {
    return function (newState) {
      if (typeof newState === 'function') {
        states[stateIndex] = newState(states[stateIndex]);
      } else {
        //普通值时
        states[stateIndex] = newState;
      }

      render();
    };
  }

  function useState(initialState) {
    //创建state
    states[stateIndex] = createState(initialState, stateIndex);

    //stateSetters数组没有内容时
    if (!stateSetters[stateIndex]) {
      //创建stateSetter并放入数组
      stateSetters.push(createStateSetter(stateIndex));
    }

    //赋值
    const _state = states[stateIndex],
      _setState = stateSetters[stateIndex];

    stateIndex++;

    return [_state, _setState];
  }

  function render() {
    //重置
    stateIndex = 0;

    ReactDOM.render(<App />, document.querySelector('#app'));
  }

  return { useState };
})();

//----------------------开发者编写区域-----------------------
const { useState } = MyReact;

function App() {
  const [count, setCount] = useState(0);
  const [flag, setFlag] = useState(0);

  return (
    <div>
      <h1>{count}</h1>
      <h1>{flag ? '打开状态' : '关闭状态'}</h1>
      <button onClick={() => setCount(count + 1)}>ADD 1</button>
      <button onClick={() => setCount((count) => count - 1)}>MINUS 1</button>
      <button onClick={() => setFlag((flag) => (flag = !flag))}>
        {flag ? '关闭' : '打开'}
      </button>
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById('app'));
